package com.stu.thread.file;

import org.springframework.util.StringUtils;

import java.io.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @projectName: learn_used_code
 * @packageName: com.stu.thread.file
 * @className: com.stu.thread.file-> FileFilterUtils
 * @createDate: 2021-12-30 18:27
 * @author: ZhangSheng
 * @version: 1.0
 * @description: Java源码文件处理过滤工具类;
 */
public class FileFilterUtils {

    /**
     * 匹配注释
     */
    private static final String MATCH = "(?<!:)\\/\\/.*|\\/\\*(\\s|.)*?\\*\\/";

    private static final String MATCH_2 = "/\\*{1,2}[\\s\\S]*?\\*/";

    private static final String XML_SUFFIX = ".xml";

    private static final String YML_SUFFIX = ".yml";

    private static final String NEW_LINE = "\\";

    private static final String LINE_FEED = "\n";

    private static final String POINT_SUFFIX = "\\.";


    /**
     * 过滤Java代码中带 /** 的注释
     * 此方法不过滤xml和yml文件
     * @param sourcePath
     * @param outTargetPath
     * @throws InterruptedException
     * @throws IOException
     */
    public static void filterFile(String sourcePath,String outTargetPath) throws InterruptedException, IOException {
        long starttime = System.currentTimeMillis();
        File file = new File(sourcePath);
        BlockingQueue<File> queue = new ArrayBlockingQueue<File>(10000);
        // 如果是文件
        if (!file.isFile()){
            queue.put(file);
            // 如果是文件夹
        }else{
            writeTonewFile(file,outTargetPath);
        }
        while (true){
            File pollFile = queue.poll();
            if (null == pollFile){
                break;
            }
            if (!pollFile.isFile()){
                File[] files = pollFile.listFiles();
                if (null != files && files.length !=0){
                    for (int i = 0; i < files.length; i++) {
                        if (!files[i].isFile()){
                            queue.put(files[i]);
                        }else{
                            writeTonewFile(files[i],outTargetPath);
                        }
                    }
                }
            }else{
                writeTonewFile(pollFile,outTargetPath);
            }
        }
        System.out.println((System.currentTimeMillis()-starttime)+ " ms");
    }

    /**
     * 拷贝文件到target路径下
     * @param file: 源文件
     * @param targetFile: 目标路径
     */
    private static void writeTonewFile(File file,String targetFile) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String firstLine = "";
        int count = 0;
        for (String line; (line = bufferedReader.readLine()) != null; ) {
            String newLine = line.replaceAll(MATCH, "");
            if (!StringUtils.hasText(newLine)){
                continue;
            }
            if (count == 0) {
                firstLine = newLine;
            }
            count = 1;
            String newLine2 = line.replaceAll("final", "");
            stringBuilder.append(newLine2).append(LINE_FEED);
        }
        String valueStr = DecodeUtils.decodeUnicode(stringBuilder.toString());
        String firstListSplit = firstLine.split(";")[0];
        String fileName = file.getName();
        String lastIndex = fileName.substring(fileName.lastIndexOf("."));
        // 验证file后缀是否为yml 和 xml
        if (!lastIndex.equals(YML_SUFFIX) && !lastIndex.equals(XML_SUFFIX)) {
            String newLine = firstListSplit.replaceAll(MATCH_2, "")
                    .replaceAll("BOOT-INF.classes.", "")
                    .replaceAll(";", "")
                    .replaceAll("package", "")
                    .trim();
            String[] split = newLine.split(POINT_SUFFIX);
            StringBuilder urlBuilder = new StringBuilder(targetFile);
            for (int i = 0; i < split.length; i++) {
                urlBuilder.append(NEW_LINE).append(split[i]);
            }
            File file2 = new File(urlBuilder.toString());
            if (!file2.exists()) {
                file2.mkdirs();
            }
            urlBuilder.append(NEW_LINE).append(file.getName());
            File fileLast = new File(urlBuilder.toString());
            fileLast.setReadable(true, false);
            fileLast.setWritable(true, false);
            fileLast.setExecutable(true, false);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileLast)));
            bufferedWriter.write(valueStr.replaceAll(MATCH_2, "")
                    .replaceAll("BOOT-INF.classes.", ""));
            bufferedWriter.flush();
        }else {
            BufferedWriter bufferedWriter = null;
            if (lastIndex.equals(XML_SUFFIX)){
                String name = file.getParentFile().getName();
                StringBuilder fileLast1 = new StringBuilder(targetFile).append(NEW_LINE).append(name);
                File xmlFile = new File(fileLast1.toString());
                if (!xmlFile.exists()){
                    xmlFile.mkdirs();
                }
                StringBuilder fileLast = fileLast1.append(NEW_LINE).append(file.getName());
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileLast.toString())));
                bufferedWriter.flush();
            }else{
                StringBuilder fileLast = new StringBuilder(targetFile);
                File ymlFile = new File(fileLast.toString());
                if (!ymlFile.exists()){
                    ymlFile.mkdirs();
                }
                fileLast.append(NEW_LINE).append(file.getName());
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileLast.toString()),"UTF-8"));
                bufferedWriter.write(valueStr);
                bufferedWriter.flush();
            }
            bufferedWriter.close();
        }
        System.out.println(file.getPath());
        bufferedReader.close();
    }


}
